﻿using KPIS.DBM;
using KPIS.GERP.GAMS.DAL;
using KPIS.GERP.GAMS.MODEL;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KPIS.GERP.GAMS.APP.App_UI.Forms
{
    public partial class CalDepreciation : System.Web.UI.Page
    {
        Commons.Main main = new Commons.Main();
        D_BGM_MAS_Source source = new D_BGM_MAS_Source();
        D_ACM_Calculate_Depreciation dep = new D_ACM_Calculate_Depreciation();
        D_ACM_GENERAL_Ledger gl = new D_ACM_GENERAL_Ledger();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void cmdCal_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtAssetCode.Text) || !dpDateStart.GetDateValue().HasValue)
            {
                main.MessageAlert(Page, "กรอกข้อมูลไม่ครบ");
                return;
            }

            DBManager dbManager = new DBManager(SystemInfo._DataProvider, ConfigurationSettings.AppSettings["ConnectionString"].ToString());
            string strAssetCode = txtAssetCode.Text;
            DateTime CalDate = dpDateStart.GetDateValue().Value;
            string strBgmYear = "2558";
            string TranGrpSeq = gl.GetNextTranGrpSeq().ToString();
            string TranCode1 = gl.GetNextTranCode("1", strBgmYear, "A");
            string TranCode2 = gl.GetNextTranCode("11", strBgmYear, "A");
            string FiscalPeriod = main.GetFiscalPeriod(CalDate);
            string TranSeq1 = "";
            string TranSeq2 = "";

            dbManager.Open();
            dbManager.BeginTransaction();
            try
            {
                dbManager.CreateParameters(1);
                dbManager.AddParameters(0, "@AssetCode", strAssetCode);

                string strSQL = @"
select a.AssetId, a.AssetCode
, a.AssetDate, a.Price, a.LifeYear, a.BgSourceId
, grp.AssetAccountId
, grp.DepreAccountId
, grp.CumdepreAccountId
, max(COALESCE(dep.CalculatedDate, a.AssetDate)) as CalculatedDate
, sum(COALESCE(dep.DepAmount, 0)) as DepAmount
from IcmAsset a
left join IcmAssetDepreciation dep on a.AssetId = dep.AssetId
inner join IcmMasResourceItem item on a.ResItemId = item.ResItemId
inner join IcmMasResourceSubGroup sub on item.ResSubGrpId = sub.ResSubGrpId
inner join IcmMasResourceGroup grp on sub.ResGrpId = grp.ResGrpId

where a.AssetCode = @AssetCode
--and a.RecordStatus <> 'D'

group by a.AssetId, a.AssetCode, a.AssetDate, a.Price, a.LifeYear, a.BgSourceId
, grp.AssetAccountId
, grp.DepreAccountId
, grp.CumdepreAccountId";
                DataTable dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                if (dtb.Rows.Count > 0)
                {
                    DataRow dr = dtb.Rows[0];
                    double Price = main.ConvertNullDouble(dr["Price"]) ?? 0;
                    double AccumDepreAmount = main.ConvertNullDouble(dr["DepAmount"]) ?? 0;
                    double LifeYear = main.ConvertNullDouble(dr["LifeYear"]) ?? 0;
                    DateTime LastCalDate = main.ConvertNullDateTime(dr["CalculatedDate"]) ?? DateTime.Today;

                    int Days = Convert.ToInt32((CalDate - LastCalDate).TotalDays);
                    double DepreAmount = (Price / (LifeYear * 365)) * Days;

                    if (Price <= DepreAmount + AccumDepreAmount)
                    {
                        DepreAmount = Price - AccumDepreAmount - 1;
                    }

                    if (DepreAmount < 0)
                    {
                        DepreAmount = 0;
                        return;
                    }

                    if (string.IsNullOrEmpty(dr["DepreAccountId"].ToString()) || string.IsNullOrEmpty(dr["CumdepreAccountId"].ToString()))
                    {
                        throw new Exception("ครุภัณฑ์รหัส " + dr["AssetCode"].ToString() + " ไม่มีการผูกบัญชีไว้");
                    }

                    var AccumDepreAccId = dr["CumdepreAccountId"].ToString();
                    var DepreAccId = dr["DepreAccountId"].ToString();

                    Depre depreInfo = new Depre()
                    {
                        BgmSourceSeq = dr["BgSourceId"].ToString(),

                        Amount = DepreAmount,
                    };

                    //depreList.Add(depreInfo);

                    dbManager.CreateParameters(7);
                    dbManager.AddParameters(0, "@AssetId", dr["AssetId"].ToString());
                    dbManager.AddParameters(1, "@CalculatedDate", CalDate);
                    dbManager.AddParameters(2, "@DepAmount", DepreAmount);
                    dbManager.AddParameters(3, "@TranGrpId", TranGrpSeq);
                    dbManager.AddParameters(4, "@RecordStatus", "W");
                    dbManager.AddParameters(5, "@CreatedBy", 1);
                    dbManager.AddParameters(6, "@CreatedWhen", DateTime.Now);

                    strSQL = @"
INSERT INTO IcmAssetDepreciation
(AssetId, CalculatedDate, DepAmount, TranGrpId, RecordStatus, CreatedBy, CreatedWhen)
values
(@AssetId, @CalculatedDate, @DepAmount, @TranGrpId, @RecordStatus, @CreatedBy, @CreatedWhen)
";

                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                    strSQL = @"
INSERT INTO acm_transection
(tran_type, fiscal_period, tran_grp_seq, tran_code, tran_date, bgm_year, bgm_source_seq, ref_no, tran_name, record_status, created_by, created_when)
values
(@tran_type, @fiscal_period, @tran_grp_seq, @tran_code, @tran_date, @bgm_year, @bgm_source_seq, @ref_no, @tran_name, @record_status, @created_by, @created_when);
select scope_identity();
";

                    dbManager.CreateParameters(12);
                    dbManager.AddParameters(0, "@tran_type", "A");
                    dbManager.AddParameters(1, "@fiscal_period", FiscalPeriod);
                    dbManager.AddParameters(2, "@tran_grp_seq", TranGrpSeq);
                    dbManager.AddParameters(3, "@tran_code", TranCode1);
                    dbManager.AddParameters(4, "@tran_date", CalDate);
                    dbManager.AddParameters(5, "@bgm_year", strBgmYear);
                    dbManager.AddParameters(6, "@bgm_source_seq", dr["BgSourceId"].ToString());
                    dbManager.AddParameters(7, "@ref_no", TranCode1);
                    dbManager.AddParameters(8, "@tran_name", "ปรับปรุงค่าเสื่อมราคาครุภัณฑ์ '" + strAssetCode + "'");
                    dbManager.AddParameters(9, "@record_status", "W");
                    dbManager.AddParameters(10, "@created_by", 1);
                    dbManager.AddParameters(11, "@created_when", DateTime.Now);

                    TranSeq1 = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0].ToString();
                    dbManager.CreateParameters(7);
                    dbManager.AddParameters(0, "@tran_seq", TranSeq1);
                    dbManager.AddParameters(1, "@amount", DepreAmount);
                    dbManager.AddParameters(2, "@record_status", "W");
                    dbManager.AddParameters(3, "@created_by", 1);
                    dbManager.AddParameters(4, "@created_when", DateTime.Now);

                    dbManager.AddParameters(5, "@account_seq1", DepreAccId);
                    dbManager.AddParameters(6, "@account_seq2", AccumDepreAccId);
                    strSQL = @"
INSERT INTO acm_transection_dtls
(tran_seq, account_seq, dr_or_cr, amount, record_status, created_by, created_when)
values
(@tran_seq, @account_seq, @dr_or_cr, @amount, @record_status, @created_by, @created_when)
";
                    strSQL = strSQL.Replace("@dr_or_cr", "'Dr'");
                    strSQL = strSQL.Replace("@account_seq", "@account_seq1");
                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                    strSQL = strSQL.Replace("@dr_or_cr", "'Cr'");
                    strSQL = strSQL.Replace("'Dr'", "'Cr'");
                    strSQL = strSQL.Replace("@account_seq1", "@account_seq2");
                    dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                }
                else
                {
                    main.MessageAlert(Page, "หาไม่เจอ");
                }
                dbManager.CommitTransaction();

                main.MessageAlert(Page, "เรียบร้อย");
                txtAssetCode.Text = "";
                txtAssetCode.Focus();
            }
            catch (Exception ex)
            {
                dbManager.RollBackTransaction();
                main.MessageAlert(Page, ex.Message);
            }
            finally
            {
                dbManager.Dispose();
            }
        }
    }
}